package com.haiheng.voiceandbook.service

import android.accessibilityservice.AccessibilityService
import android.content.Intent
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import com.haiheng.voiceandbook.Constants


/**
 *
 * @Des:
 * @Author: hwz
 * @Date:2023/10/9 0009
 * @Version: 1.0
 */


class MyAccessibilityService : AccessibilityService() {
    companion object {
        private const val TAG = "MyAccessibilityService"
    }
    override fun onAccessibilityEvent(event: AccessibilityEvent) {
        Log.d(TAG, "onAccessibilityEvent event  : ${event.toString()}")
        if (event.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            // 当窗口状态变化时
            Log.d(TAG, "onAccessibilityEvent : ${event.eventType}")
            val packageName = event.packageName.toString()

            // 判断应用包名是否是你的应用
            if (packageName == "com.haiheng.voiceandbook") {
                // 应用在前台
                Log.d(TAG, "应用在前台")
                // 在这里执行你需要的逻辑
            } else {
                // 应用不在前台
                Log.d(TAG, "应用不在前台:${Constants.isExitOpenApp()}")
                // 在这里执行你需要的逻辑
                if (Constants.isExitOpenApp()){
                    startApp()
                }
            }
        }
    }

    override fun onInterrupt() {
        // 当服务中断时调用
        Log.d(TAG, "当服务中断时调用")
    }

    private fun startApp() {
        // 重新启动应用
        val launchIntent = packageManager.getLaunchIntentForPackage(packageName)
        launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        launchIntent?.let { startActivity(it) }
    }
}
